<script setup>
import {onMounted,ref} from "vue";
import axios from '../api'
import _ from 'lodash'
import {useRoute,useRouter} from "vue-router";


const router=useRouter();
const route=useRoute();
//获取角色信息
const role=route.query;
console.log(route.query);

//记录角色信息对象
const targetObj=ref({});
//页面中展示树形数据的绑定数据
const treeData=ref([]);
//记录选中的数据
const checkData=ref([]);

//页面组件挂载完成后
onMounted(async  function (){
    //查询当前角色的信息
    targetObj.value=await  axios.roleByID(role.id);
    //将所有权限信息数据转换格式
    treeData.value=convertData(await  axios.permissionList());
    //封装属性结构中默认选中的数据
    defaultCheckData();
})
//将权限信息转成树形数据信息
function convertData(list){
  let result=[];
  if(list){
    for(let item of  list){
      let obj={};
      obj.id=item.id;
      obj.label=item.permname+"-"+item.permkey+"-"+item.id;
      if(item.children){
        obj.children=convertData(item.children);
      }
      result.push(obj);
    }
  }
  return result;
}
function defaultCheckData(){
    for(let item of targetObj.value.permissions){
      checkData.value.push(item.id);
    }
}

const defaultProps = {
  children: 'children',
  label: 'label',
}
function checkChange(node,check,children){
    let arr=checkData.value;
    if(check){
      arr.push(node.id);
    }else {
      for (let i=0;i<arr.length;i++) {
          if(arr[i]==node.id){
            arr.splice(i,1);
          }
      }
    }
  console.log(checkData.value);
}


function submitData(){
    //处理好要提交的数据
    let data={};
    data.id=targetObj.value.id;
    data.permissions=[];
    //checkData.value  [1,2,4,6,7,9]
  //item 1   2  4   6    7   9
    for(let item of checkData.value){
         let obj={};
         obj.id=item;
         //obj===   {id:1}
      data.permissions.push(obj);
      //data.permissions   [{id:1},{id:2}....]
      //data    {id:1,permisssions:[{id:1},{id:2}]}
    }

    axios.assignPermisssion(data);
    router.push({path:"/rolePage"})
}

</script>

<template>
  <el-tree
      style="max-width: 600px"
      :data="treeData"
      show-checkbox
      node-key="id"
      :check-strictly="true"
      :default-expanded-keys="[1]"
      :default-checked-keys="checkData"
      :props="defaultProps"
      @check-change="checkChange"
  />
  <el-button type="primary" @click="submitData">Primary</el-button>
</template>

<style scoped>

</style>